﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Globalization;
using System.Text.RegularExpressions;
using System.Web;
using System.Data;
using System.Web.UI;
using System.IO;
using System.Data.SqlClient;

namespace System
{
    public static class StringHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fields">列集合;以","分割,""、null或"*"表示所有列</param>
        /// <returns>结果</returns>
        public static List<string> GetListFromString(string fields)
        {
            return GetListFromString(fields, ',');
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fields">列集合;以","分割,""、null或"*"表示所有列</param>
        /// <param name="split"></param>
        /// <returns>结果</returns>
        public static List<string> GetListFromString(string fields, char split)
        {
            string[] array = fields.Trim(split).Trim().Split(split);
            List<string> List = new List<string>();
            foreach (string field in array)
            {
                List.Add(field.ToUpperInvariant());
            }
            return List;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="list">待处理对象集合</param>
        /// <returns>结果</returns>
        public static List<string> CuteParentheses(List<string> List)
        {
            for (int i = 0; i < List.Count; i++)
            {
                List[i] = List[i].Trim('[').Trim(']').Trim('(').Trim(')').Trim('{').Trim('}').Trim(',').Trim(';').Trim('\'').Trim('"');
            }
            return List;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fields">列集合;以","分割,""、null或"*"表示所有列</param>
        /// <param name="field"></param>
        /// <returns>结果</returns>
        public static bool IsFieldEnable(List<string> fields, string field)
        {
            bool result = false;

            foreach (string temp in fields)
            {
                if (temp.ToUpperInvariant() == field.ToUpperInvariant())
                {
                    result = true;
                    break;
                }
            }
            //var fie = from temp in ListFields
            //          where temp.ToUpperInvariant() == field.ToUpperInvariant()
            //          select temp;
            //if (fie != null && fie.ToArray<string>().Length > 0)
            //    result = true;
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <returns>结果</returns>
        public static int GetStrLength(string str)
        {
            ASCIIEncoding n = new ASCIIEncoding();
            byte[] b = n.GetBytes(str);
            int l = 0;  // l 为字符串之实际长度
            for (int i = 0; i < b.Length; i++)
            {
                if (b[i] == 63)  //判断是否为汉字或全脚符号
                {
                    l++;
                }
                l++;
            }

            return l;
        }

        #region  过虑非法字符

        /// <summary>
        /// 过虑非法字符
        /// </summary>
        /// <param name="paraValue"></param>
        /// <returns>结果</returns>
        public static string SafeRequest(string paraValue)
        {
            string SafeRequest = "";
            paraValue = paraValue.Replace("'", "''");
            paraValue = paraValue.Replace("select ", "");
            paraValue = paraValue.Replace("Add ", "");
            paraValue = paraValue.Replace("delete ", "");
            paraValue = paraValue.Replace("count(", "");
            paraValue = paraValue.Replace("drop table ", "");
            paraValue = paraValue.Replace("update ", "");
            paraValue = paraValue.Replace("truncate ", "");
            paraValue = paraValue.Replace("asc(", "");
            paraValue = paraValue.Replace("mid(", "");
            paraValue = paraValue.Replace("char(", "");
            paraValue = paraValue.Replace("xp_cmdshell", "");
            paraValue = paraValue.Replace("exec", "");
            paraValue = paraValue.Replace("exec master", "");
            paraValue = paraValue.Replace("net localgroup administrators", "");
            paraValue = paraValue.Replace(" and ", "");
            paraValue = paraValue.Replace("net user", "");
            paraValue = paraValue.Replace(" or ", "");
            paraValue = paraValue.Replace(" &nbsp; ", "");

            paraValue = paraValue.Replace(";", "");
            paraValue = paraValue.Replace("'", "");
            paraValue = paraValue.Replace("&", "");
            paraValue = paraValue.Replace("%20", "");
            paraValue = paraValue.Replace("--", "");
            paraValue = paraValue.Replace("==", "");
            paraValue = paraValue.Replace("<", "");
            paraValue = paraValue.Replace(">", "");
            paraValue = paraValue.Replace("%", "");

            SafeRequest = paraValue;
            return SafeRequest;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="paraValue"></param>
        /// <param name="maxLen"></param>
        /// <returns>结果</returns>
        public static string SafeRequest(string paraValue, int maxLen)
        {
            string safeRequest = SafeRequest(paraValue);

            if (safeRequest.Length > maxLen)
            {
                safeRequest = safeRequest.Substring(0, maxLen - 1);
            }
            return safeRequest;
        }


        public static string DeleteHTMLMarks(string Htmlstring)
        {
            //删除脚本  
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML  
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
            return Htmlstring;
        }


        #endregion



        public static string FormatMoney(int money)
        {
            if (money == 0)
            {
                return "0";
            }
            else
            {
                return money.ToString("###,###");
            }
        }

        public static string FormatFloatMoney(float money)
        {

            if (money == 0)
            {
                return "0";
            }
            else
            {
                return money.ToString("###,###");
            }


        }

        public static void DeleteFile(Page page, string foldername, string filename)
        {
            if (foldername == "")
            {
                filename = page.Server.MapPath(filename);
            }
            else
            {
                filename = page.Server.MapPath(foldername) + filename;
            }
            FileInfo fi = new FileInfo(filename);
            if (fi.Exists)
            {
                fi.Delete();
            }
        }

        public static string RepeatString(int count)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i < count; i++)
            {
                sb.Append("|----");
            }
            return sb.ToString();
        }


        public static string FormatBlankString(string str)
        {
            if (str == "")
            {
                str = "0";
            }
            return str;
        }

        public static string FormatObjToString(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            return obj.ToString();
        }


        public static int FormatBlankStringToint(string str)
        {
            try { return int.Parse(str); }
            catch (Exception e) { return 0; }
        }

        public static int FormatObjStringToint(object str)
        {
            try { return int.Parse(str.ToString()); }
            catch (Exception e) { return 0; }
        }

        public static long FormatObjStringTolong(object str)
        {
            try { return long.Parse(str.ToString()); }
            catch (Exception e) { return 0; }
        }
        public static int FormatObjToInt(object str)
        {
            try { return int.Parse(str.ToString()); }
            catch (Exception e) { return 0; }
        }
        public static decimal FormatObjToDecimal(object str)
        {
            try { return decimal.Parse(str.ToString()); }
            catch (Exception e) { return 0; }
        }

        public static bool FormatObjToBool(object bln)
        {
            if (bln == null)
            {
                return false;
            }
            else
            {
                return bln.ToString() == "1" || bln.ToString().ToUpper() == "TRUE";

            }

        }

        /*截取字符串*/
        public static string SubString(object s, int length)
        {
            if (s == null)
            {
                return string.Empty;
            }
            else
            {
                string rs = s.ToString();
                return rs.Length > length ? (rs.Substring(0, length)) : rs;
            }

        }

        /*截取字符串,给定的字符串大于length时，后加省略号*/
        public static string SubString(object s, int length, bool hasAdditional)
        {
            if (s == null)
            {
                return string.Empty;
            }
            else
            {
                string rs = s.ToString();
                if (rs.Length > length)
                {
                    rs = rs.Substring(0, length);
                    if (hasAdditional)
                    {
                        rs = rs + "...";
                    }
                }

                return rs;
            }

        }

        /*将字符型日期输出为指定长度的日期*/
        public static string FormatDateTimeStringToString(string dateTime, string format)
        {
            try
            {
                //DateTime.Parse(DateTime)
                return DateTime.Parse(dateTime).ToString(format);
            }
            catch (Exception e)
            {
                return dateTime;
            }
        }

        /*将字符串转成日期*/
        public static DateTime FormatStringToDate(string dateTime)
        {
            try
            {
                //如果输入的日期如0001-01-01不允许,返回1900-01-01
                DateTime dtime = DateTime.Parse(dateTime);
                if (dtime <DateTime.Parse( "1900-01-01"))
                {
                    return DateTime.Parse("1900-01-01");
                }
                if (dtime > DateTime.Parse("2099-01-01"))
                {
                    return DateTime.Parse("2099-01-01");
                }
                return dtime;
            }
            catch (Exception e)
            {
                return DateTime.Now;
            }
        }

        /*将字符型日期输出为指定年月日*/
        public static string FormatStringDateTimeToDate(string dateTime)
        {
            return FormatDateTimeStringToString(dateTime, "yyyy-MM-dd");
        }

        //格式化字符串
        public static string FormatStringToHid(string tel)
        {
            return hidStr(tel, 3, 2);
        }

        //整数相除
        public static decimal intDevison(int son, int mother)
        {
            if (mother == 0)
            {
                return 0;
            }
            else
            {
                try { return decimal.Parse(son.ToString()) / mother; }
                catch (Exception e) { return 0; }
            }
        }
        //得到百分数
        public static string GetPercent(int son, int mother)
        {
            return intDevison(son, mother).ToString("p");
        }

        //startDislen:开头显示几位 endDisLen :结尾显示几位，中间以"*"代替
        public static string hidStr(string tel, int startDisLen, int endDisLen)
        {

            if (!string.IsNullOrEmpty(tel) && tel.Length > (startDisLen + endDisLen))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(tel.Substring(0, startDisLen));
                for (int i = 0; i < tel.Length - (startDisLen + endDisLen); i++)
                {
                    sb.Append("*");
                }
                sb.Append(tel.Substring(tel.Length - endDisLen, endDisLen));
                return sb.ToString();
            }
            else
            {
                return tel;
            }
        }

        //将DataTable转换成JSON数据,按X轴，Y轴,DataTable第一列为X轴，第二列为Y轴
        public static string FormatDataTableToChartJson(DataTable dt)
        {
            if (dt == null || dt.Rows.Count < 0 || dt.Columns.Count < 2)
            {
                return string.Empty;
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append(",{");
                //x轴数据
                sb.Append('x');
                sb.Append(":");
                sb.Append("'");
                sb.Append(dt.Rows[i][0].ToString());
                sb.Append("',");
                //
                sb.Append('y');
                sb.Append(":");
                sb.Append("'");
                sb.Append(dt.Rows[i][1].ToString());
                sb.Append("'");
                sb.Append("}");
            }
            if (sb.ToString().Length > 1)
            {
                return sb.ToString().Substring(1, sb.ToString().Length - 1);
            }
            else
            {
                return string.Empty;
            }

        }

        //生成存储过程语句，以方便在数据库中进行测试
        public static string GetStoredProcedureText2(SqlParameter[] _SqlParameter, string storeName)
        {
            if (_SqlParameter == null)
            {
                return "";
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("Exec dbo.");
            sb.Append(storeName);
            sb.Append("  ");
            for (int i = 0; i < _SqlParameter.Length; i++)
            {
                if (_SqlParameter[i] != null && _SqlParameter[i].SqlValue != null)
                {
                    sb.Append(_SqlParameter[i].ParameterName);
                    sb.Append("=\'");
                    sb.Append(_SqlParameter[i].SqlValue);
                    sb.Append("\',");
                }
            }
            return sb.ToString().Substring(0, sb.Length - 1);
        }

     

    }
}
